<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Job_model extends My_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->model_name = "任务表";
        $this->tablename = "jobs";
    }

    public function getpage($page, $key = "")
    {

        $where = ["status<> " => 4];
        $key = ["note" => $key,
            "id" => $key,
            "job_type" => $key,
            "addtime" => $key,
            "filter" =>$key,
        ];
        return $this->get_items_by_page($where, $page, "backend/crons/index", "status asc,id desc", [], $key);
    }

    public function getstarting()
    {
        $where = ["status" => 1];
        return $this->get_items_by_where($where);
    }

    public function getwaiting()
    {
        $rjobs = [];
        $where = "status in (0,5)";
        $jobs = $this->get_items_by_where($where, "status asc,id desc");
        if ($jobs):
            foreach ($jobs as $job) {
                if ($job["status"] == 5 && (time() - strtotime($job["endtime"])) < 60 * 60 * 24) {
                    continue;
                }
                $rjobs[] = $job;
            }
        endif;
        return $rjobs;
    }


    public function getone()
    {
        $where = ["status" => 1];
        $background = $this->get_items_by_where($where);
        if ($background && count($background) >= 2) {
            return;
        }
        $where = ["status" => 0];
        return $this->get_item_by_where($where);
    }

    public function start($job)
    {
        return $this->update($job["id"], ["starttime" => date("Y-m-d H:i:s"), "status" => 1]);
    }

    public function limitupdate()
    {
        $where = ["status" => 5];
        $jobs = $this->get_items_by_where($where);
        if ($jobs) {
            foreach ($jobs as $job) {
                $this->update($job["id"], ["status" => 0]);
            }
        }
    }

    public function done($job)
    {
        return $this->update($job["id"], ["status" => 2, "endtime" => date("Y-m-d H:i:s")]);
    }

    public function addjobcount($jid)
    {
        $this->auto_add("donecount", ["id" => $jid]);
    }

    public function getall()
    {

        $where = [];

        return $this->get_items_by_where($where);
    }

    public function delete($id)
    {

        return true;
    }

    public function getitembyid($id)
    {
        $where = array("id" => $id);

        return $this->get_item_by_where($where);
    }


    public function create($data)
    {
        if (!isset($data["addtime"])) {
            $data["addtime"] = date("Y-m-d H:i:s");
        }

        return $this->add_item($data);
    }

    public function update($id, $data)
    {

        if (is_array($id)) {
            $where = "id in (" . implode(",", $id) . ")";

        } else {
            $where = array("id" => $id);

        }
        return $this->update_item($where, $data);

    }


}
